import { queryMy, queryStatus, queryAddQuery, queryRemove } from '@/api/goods'

// 购物车模块
export default {
  namespaced: true,
  state: {
    cartList: [], // 购物车列表
    id: []
  },
  mutations: {
    SET_CART_LIST (state, list) {
      state.cartList = list
    },
    id (state, id) {
      state.id = id
    }
  },
  actions: {
    // 获取购物车列表
    async getCartList ({ commit }) {
      const res = await queryMy()
      console.log(res)
      commit('SET_CART_LIST', res)
    },
    // 修改购物车状态
    async changeCartChecked ({ commit }, { uid, isChecked }) {
      console.log(uid, isChecked)
      await queryStatus({ uid, isChecked })
    },
    // 修改购物车所有状态
    changeAllChecked ({ dispatch, state }, isChecked) {
      // 定义数组用于 保存 请求结果
      const promise_arr = []
      // 循环购物车 对每个商品进行修改
      state.cartList.forEach(cart => {
        // 判断商品状态与要修改的状态是否一致
        if (cart.checked === isChecked) return
        // 调用多次 修改购物车状态 action
        promise_arr.push(dispatch('changeCartChecked', { uid: cart.id, isChecked }))
      })
      // 将请求后的 promise对象返回
      return Promise.all(promise_arr)
    },
    async queryAddQuery ({ commit, dispatch }, { id, userId }) {
      await queryAddQuery(id, { userId })
    },
    async queryAddQueryAll ({ commit, dispatch, state }, { userId }) {
      console.log(userId)
      const promise_arr = []
      state.id.forEach(cart => {
        promise_arr.push(dispatch('queryAddQuery', { id: cart.id, userId }))
      })

      return Promise.all(promise_arr)
    },
    async queryRemove ({ commit }, id) {
      if (!id) return alert('id必须有')
      await queryRemove(id)
    },
    async queryRemoveAll ({ commit, dispatch, state }, id) {
      const promise_arr = []
      state.id.forEach(cart => {
        promise_arr.push(dispatch('queryRemove', cart.id))
      })

      return Promise.all(promise_arr)
    },
    filterId ({ commit, state }) {
      const id = state.cartList.filter((item) => {
        return item.checked === '1'
      })
      commit('id', id)
    }
  },
  getters: {
  }
}
